<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2020/1/2
 * Time: 20:40
 */

namespace app\common\model;

use app\common\lib\astrolog\Calendar;
use Exception;
use think\Log;
use XznsTools\cache\CacheManage;

/**
 * 星象变动
 * Class AstroChange
 * @package app\common\model
 */
class AstroChange extends BaseCache
{
    private const LOG_PRE = '小程序MiniDateText Model 异常：';

    protected $table = 'wechat_backup_07_18_14_43_00.app_astro_change';
    protected $cacheModel = 'mini.astro';
    /**
     * 星象变动支持的类型
     * 1.行星换座 [例如：火星进入射手座]
     * 2.行星顺逆行变换 [例如：天王星在金牛座顺行]
     * 3.日食
     * 4.月食
     * 5.新月
     * 6.满月
     * [3-6都是星座]
     * @var array
     */
    private $supportType = [1, 2, 3, 4, 5, 6];

    private $cacheModule = 'astro.change';

    /**
     * 获取星象变动词条
     * @return mixed
     * @throws Exception
     */
    public function getTodayAstroChange()
    {
        $date = date('Y-m-d');

        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $date)->getDataAndSet(function () use ($date)
        {
            return $this->getAstroChangeFromDB($date);
        });
        $data = json_decode($data, true);
        if (!$data)
        {
            $data = [];
        }
        return $data;
    }

    /**
     * 从数据库获取星象变动词条
     * @param $date
     *      1  行星换座
     *      2  行星 逆行/顺行
     *      3  日食
     *      4  月食
     *      5  新月
     *      6  满月
     * @return string
     */
    private function getAstroChangeFromDB($date): string
    {
        $data = '';
        try
        {
            //东八区的时间戳，数据库中存的是零时区的，所以需要转换
            $yesterday = date('Y-m-d', strtotime('-1 day', strtotime($date)));//前一天
            // 获取北京时间该天内的星象变动数据
            $result = $this->whereTime('time', 'between', [$yesterday . ' 16:00', $date . ' 16:00'])->where([])->select();
            $result = json_decode(json_encode($result, true), true);
            if ($result)
            {
                //type  1.行星换座[例如：火星进入射手座]、2.行星顺逆行变换[例如：天王星在金牛座顺行]、3.日食、4.月食、5.新月、6.满月[3-6都是星座]
                $data = (new Calendar())->transerData($result);
                $data = json_encode($data, true);
            }
        }
        catch (Exception $e)
        {
            Log::write(self::LOG_PRE . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
        }
        return $data;
    }

    public function getAstroChangeData($date = '', $isTranser = false, $need = [])
    {
        if (!$date)
        {
            // 若日期未传，则默认为北京时间当天
            $date = date('Y-m-d');
        }
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModule, $date)->getDataAndSet(function () use ($date)
        {
            return $this->getOriginDataFromDB($date);
        });
        is_string($data) && $data = json_decode($data, true);
        // 获取交集
        $intersect = array_intersect($need, $this->supportType);
        // 仅返回需要的类型数据
        if (!empty($data) && !empty($intersect))
        {
            $tmp = [];
            foreach ($data as $d)
            {
                in_array($d['type'], $intersect) && $tmp[] = $d;
            }
            $data = $tmp;
        }
        if ($isTranser === true && !empty($data))
        {
            // 将数据转换为可阅读格式
            $data = (new Calendar())->transerData($data);
        }
        return $data;
    }

    /**
     * 从数据库获取当天所有的星象变动
     * @param $date
     * @return array
     */
    public function getOriginDataFromDB($date)
    {
        try
        {
            //东八区的时间戳，数据库中存的是零时区的，所以需要转换
            $yesterday = date('Y-m-d', strtotime('-1 day', strtotime($date)));// 前一天
            $result = $this->whereTime('time', 'between', [$yesterday . ' 16:00', $date . ' 16:00'])->select();
            $data = json_decode(json_encode($result, true), true);
        }
        catch (Exception $e)
        {
            $data = [];
            Log::write('星象变动数据获取异常：' . $e->getMessage(), 'error');
        }
        return $data;
    }
}
